package com.itcast.util;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

/**
 * JDBC 工具类
 */
public class jdbcUtils {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;

    /**
     * 文件读取，只读取一次即可拿到数据，使用静态代码块。
     */
    static {
        try {
            // 读取资源文件
            // 1.创建 Properties 对象
            Properties properties = new Properties();
            // 获取 src 路径下文件的方式 ---> ClassLoader 类加载器
            ClassLoader classLoader = jdbcUtils.class.getClassLoader();
            URL resource = classLoader.getResource("jdbc.properties");
            assert resource != null;
            String path = resource.getPath();
//            System.out.println(path);
            // 2.加载文件
//            properties.load(new FileReader("/Users/oscar/Desktop/HQWork/学习资料/code/day05/jdbc.properties"));
            properties.load(new FileReader(path));
            // 3.获取数据，赋值
            url = (String) properties.get("url");
            user = (String) properties.get("user");
            password = (String) properties.get("password");
            driver = (String) properties.get("driver");

            // 注册驱动
            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     *
     * @return 连接对象
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }

    /**
     * 释放资源
     *
     * @param stmt
     * @param connection
     */
    public static void close(Statement stmt, Connection connection) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 释放资源
     *
     * @param rs
     * @param stmt
     * @param connection
     */
    public static void close(ResultSet rs, Statement stmt, Connection connection) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
